package com.gangye;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Classname FileToZip
 * @Description 压缩文件，将目录sourcePath下的文件(不能含有目录)打包压缩成文件名为fileName的zip文件，并保存到zipFilePath目录下
 * @Date 2020/4/13 14:20
 * @Created by gangye
 */
public class FileToZip {
    /**
     * sourcePath为要打包扫描的目录文件，zipFileName为
     * @param sourcePath
     * @param zipFilePath
     * @param fileName
     * @return boolean
     */
    public static boolean fileToZip(String sourcePath, String zipFilePath, String fileName) {
        boolean flag = false;
        File sourceFile = new File(sourcePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        if(!sourceFile.exists()){
            System.out.println("没有此文件目录");
        } else{
            try {
                File zipFile = new File(zipFilePath+"/"+fileName+".zip");
                if (zipFile.exists()){
                    System.out.println(zipFilePath+"目录下已存在名字为："+fileName+"的压缩文件。");
                    zipFile.delete();
                }
                File[] sourceFiles = sourceFile.listFiles();
                if (null==sourceFiles || sourceFiles.length<1){
                    System.out.println("待压缩的文件的目录："+sourcePath+"里没有文件，无需压缩.");
                }else{
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024*10];
                    for (int i= 0;i<sourceFiles.length;i++){
                        //创建ZIP实体，并添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                        zos.putNextEntry(zipEntry);
                        //读取待压缩的文件并写进压缩包里
                        fis = new FileInputStream(sourceFiles[i]);
                        bis = new BufferedInputStream(fis,1024*10);
                        int read = 0;
                        while ((read=bis.read(bufs,0,1024*10))!= -1){
                            zos.write(bufs,0,read);
                        }
                    }
                    flag = true;
                }
            } catch (FileNotFoundException fe){
                fe.printStackTrace();
            } catch (IOException ie){
                ie.printStackTrace();
            } finally {
                try {
                    if (null != bis) bis.close();
                    if (null != zos) zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }
}
